import * as echarts from '../../ec-canvas/echarts';
import {request} from "../../api/request";

// 定义一个函数来处理文本并替换目标字符串
function highlightTargets(text, targets) {
    const processed = {};
    let result = text;
    targets.forEach(keyword => {
        if (!processed[keyword]) {
            const regex = new RegExp(keyword, 'i');
            result = result.replace(regex, match => {
                processed[keyword] = true; // 标记已处理
                return `<span style="color:red">${match}</span>`;
            });
        }
    });
    return result;
}

function setOption(chart, data) {
    // 假设 data 包含 originValueList 和 score
    const {originValueList, score} = data;
    const seriesData = originValueList.map((name, index) => ({
        value: score[index],
        name: name
    }));
    const option = {
        title: {
            text: '关键字',
            left: 'center',
            top: "10px"
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: ({d}%)'
        },
        series: [
            {
                name: '分类数据',
                type: 'pie',
                radius: ['50%', '70%'], // 内外半径
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '16',
                        fontWeight: 'bold'
                    }
                },
                data: seriesData
            }
        ]
    };
    chart.setOption(option);
}

Page({
    data: {
        title: '',
        content: '',
        tag: '',
        result: '',
        isFake: true,
        newsId: "",
        loading: false,
        modelExplain: '', // 新增字段，用于存储模型返回的结果
        ec: {
            lazyLoad: true, // 禁用懒加载
        },
        pieChart: null, // 存储饼状图实例
        isPie: true
    },
    initPieChart(result) {
        this.selectComponent('#pieChart').init((canvas, width, height, dpr) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            setOption(chart, result);

            // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
            this.chart = chart;

            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return chart;
        });
    },

    filter: function (result) {
        // 创建一个数组来存储需要移除的索引
        const indicesToRemove = [];
        if (typeof (result) === 'string') {
            result = JSON.parse(result)
        }
        const {originValueList, position, score} = result
        // 遍历 originValueList，找到所有 [cls] 的索引
        originValueList.forEach((value, index) => {
            if (value === '[CLS]' || value === '[SEP]') {
                indicesToRemove.push(index);
            }
        });

        // 根据索引移除 originValueList、position 和 score 中的元素
        const filteredOriginValueList = originValueList.filter((_, index) => !indicesToRemove.includes(index));
        const filteredPosition = position.filter((_, index) => !indicesToRemove.includes(index));
        const filteredScore = score.filter((_, index) => !indicesToRemove.includes(index));

        // 返回过滤后的结果
        return {
            ...result,
            originValueList: filteredOriginValueList,
            position: filteredPosition,
            score: filteredScore
        };
    },

    onLoad: function (options) {
        // 获取传递过来的 user 参数
        const newsStr = options.news;
        // 将 JSON 字符串反序列化为对象
        const news = JSON.parse(decodeURIComponent(newsStr));
        console.log(news)
        const result = this.filter(news.result)
        console.log("filter之前", result)
        this.setData({
            title: news.title,
            content: highlightTargets(news.content, result.originValueList),
            tag: news.tag,
            isFake: result.isFake,
            result: result,
            newsId: news.newsId,
            modelExplain: news.llmExplain || ""
        });
        console.log("filter之后", this.data.result)
        console.log(this.data)
        this.initPieChart(result)
    },


    exchange: function () {
        const isPie = this.data.isPie
        if (isPie) {
            // echarts.dispose()
            this.setData({
                isPie: !isPie
            })
        } else {
            this.setData({
                isPie: !isPie
            })
            this.initPieChart(this.data.result)
        }
    },
    // 调用外部模型接口
    explain: function () {
        this.setData({loading: true})
        let loading = true;
        const url = '/news/explain_stream'
        request({
            url,
            method: 'POST',
            data: {"newsId": this.data.newsId},
            enableChunked: true, // 启用分块接收
            fail: (err) => {
                // 隐藏加载提示
                this.setData({loading: false})
            },
            onChunkReceived: (res) => {
                // Uint8Array转为text格式
                const arrayBuffer = res.data;
                let texts;
                if (wx.getDeviceInfo().platform === "devtools") {
                    let decoder = new TextDecoder("utf-8");    // 本地开发者工具使用
                    texts = decoder.decode(arrayBuffer);   // 本地开发者工具使用
                } else {
                    texts = this.arrayBufferToString(arrayBuffer); // 真机使用
                }
                // 看一下 打印出来的结果
                texts = texts.split("\n"); // 将接收到的字符串按换行符分割成数组
                // 处理每个以 'data: ' 开头的字符串
                texts.forEach((text, index) => {
                    if (text && text.trim().length > 0) {
                        try {
                            const jsonString = text.replace(/^data:\s*/, ""); // 去掉前缀
                            // 检查 jsonString 是否有效 JSON
                            if (
                                jsonString.trim().startsWith("{") &&
                                jsonString.trim().endsWith("}")
                            ) {
                                const jsonData = JSON.parse(jsonString);
                                const content = jsonData.choices[0].delta.content;
                                if (content) {
                                    if (loading) {
                                        // 隐藏加载提示
                                        this.setData({loading: false})
                                        loading = false;
                                    }
                                    const modelExplain = this.data.modelExplain + content;
                                    this.setData({
                                        modelExplain
                                    });
                                }
                            }
                        } catch (error) {
                            console.error("解析 JSON 时出错:", error);
                            console.log("原始文本:", text); // 输出原始文本以便调试
                        }
                    }
                });
                // listener(text)

            }
        })
    },
    arrayBufferToString: function (arr) {
        let i;
        if (typeof arr === "string") {
            return arr;
        }
        const dataView = new DataView(arr);
        const ints = new Uint8Array(arr.byteLength);
        for (i = 0; i < ints.length; i++) {
            ints[i] = dataView.getUint8(i);
        }
        let str = "",
            _arr = ints;
        for (i = 0; i < _arr.length; i++) {
            if (_arr[i]) {
                const one = _arr[i].toString(2),
                    v = one.match(/^1+?(?=0)/);
                if (v && one.length === 8) {
                    const bytesLength = v[0].length;
                    let store = _arr[i].toString(2).slice(7 - bytesLength);
                    for (let st = 1; st < bytesLength; st++) {
                        if (_arr[st + i]) {
                            store += _arr[st + i].toString(2).slice(2);
                        }
                    }
                    str += String.fromCharCode(parseInt(store, 2));
                    i += bytesLength - 1;
                } else {
                    str += String.fromCharCode(_arr[i]);
                }
            }
        }
        return str;
    },
    // 分享功能
    onShareAppMessage: function () {
        return {
            title: '睿鉴AI鉴别报告',
            path: '/pages/result/result?content=' + encodeURIComponent(this.data.content)
        };
    },

    // 分享按钮点击事件
    shareResult: function () {
        wx.showToast({
            title: '分享成功',
            icon: 'success'
        });
    }
});